import requests
import time
import traceback
import random
import threading

import numpy as np
from transformers import BertTokenizer

request_url = 'http://127.0.0.1:8080/infer'

res_list = []
tps_list = []
use_time_list = []
success = 0
error = 0
error_nan = 0
error_time = 0
tmp = []
result_lis = []

def send_request():
    try:
        n = random.randint(0, 39)

        json_data = {
            "appealRegion":"本市",
             "classID": "1334-1528-3049-4880",
            "content":"市民来电反映：称上述地址全天都会车辆在路边乱停车，导致该处接送学生的家长行驶非常不便，市民表示学校方面已多次向康桥镇政府反映该问题，但一直没有得到解决，市民表示自己也向公安部门反映乱停车问题，但被告知因该道路建成后没有验收交付，路段无标识标线，该情况不属于违法停车，公安机关无法进行处罚。但市民表示现场实际情况就是乱停车影响了通行次序，市民诉求：希望管理部门核实尽快验收交付该路段，以便公安机关进行执法，解决乱停车问题。",
            "class4": "科教文卫类-文广影视-文化产业管理-游戏动漫"
            }

        request_res = requests.post(request_url, json=json_data).json()
        print("success! return data:", request_res)
        return request_res['class'],n
    except Exception as e:
        traceback.print_exc()

tokenizer = BertTokenizer.from_pretrained("roberta_ch")

def to_numpy(tensor):
    return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
text = "宝山区,建设交通类,住房保障,物业服务管理,物业维修添置,市民来电反映:其为上述地址居民，其房屋卫生间房顶腐烂，现在上方有泥土掉落，其卫生间高达4米，掉落物品会直接掉落在市民头上，存在安全隐患，诉求：管理部门核实，尽快对市民家中卫生间进行维修"
data = tokenizer(text,return_tensors='pt')
# tokens_tensors, token_types_tensors,masks_tensors = data['input_ids'],data['token_type_ids'],data['attention_mask']
tokens_tensors,masks_tensors = data['input_ids'],data['attention_mask']

tokens_id = to_numpy(tokens_tensors.int()).astype(np.int64)
# token_type_ids = to_numpy(token_types_tensors.int()).astype(np.int64)
attention_mask = to_numpy(masks_tensors.int()).astype(np.int32)


def send_request_http():
    n = random.randint(0, 39)
    request_data = {
	"inputs": [
        {
            "name": "input_ids",
            "shape": tokens_id.shape,
            "datatype": "INT64",
            "data": tokens_id.tolist()
	    },
        {
            "name": "attention_mask",
            "shape": attention_mask.shape,
            "datatype": "INT32",
            "data": attention_mask.tolist()
        }
    ],
	"outputs": [{"name": "output"}]
    }
    res = requests.post(url="http://172.31.30.3:8000/v2/models/paidan_129_cls/versions/1/infer",json=request_data).json()
    return res['outputs'][0]['data'],n
    # return res['outputs'],n

# 开始时间
start = time.time()


def run(i):
    global res_list, tps_list, use_time_list, success, error, error_nan, error_time, result_lis
    tt = time.time()
    dic = {}
    results, num = send_request()
    # results, num = send_request_http()

    end_time = time.time()
    # results = results.flatten()
    print("num:", num)
    if len(results) !=7:
        print("ERROR!!!!ensemble_output shape:",len(results))
        # if error_nan == 100:
        #     result_lis = pd.DataFrame(result_lis)
        #     result_lis.to_excel("box_0207_2.xlsx", index=False)
        # dic['boxes'] = results.tolist()
        # dic['n'] = num
        # result_lis.append(dic)
        error_nan += 1
        error += 1
        return None
    if end_time - tt > 5:
        error_time += 1
        error += 1
        # return None
    # if error == 30:
    #     re = pd.DataFrame(tmp)
    #     re.to_excel("errorboxes1.xlsx", index=False)
    #     print("produce errorboxes1.xlsx")
    # feature = np.frombuffer(results.as_numpy("prob"), dtype=np.float32)
    # print(results)

    res_list.append([i, end_time - tt, t, results])

    tps = len(res_list) / (time.time() - start)
    tps_list.append(tps)
    use_time_list.append(end_time - tt)
    print(end_time - tt)

    # print(resp)
    # print('tps :{} max : {} use : {}'.format(tps,max(tps_list),time.time()-tt))
    # print('avg_use:{},min_use:{},max_use:{},tps:{}'.format(sum(use_time_list) / len(use_time_list),
    #                                                                min(use_time_list), max(use_time_list),
    #                                                                max(tps_list)))
    print('#' * 30)
    print('成功率 : {}%'.format((len(res_list) / (len(res_list) + error)) * 100))
    print('cnt : {} , error : {} , error_nan : {} , error_time : {}'.format(len(res_list) + error, error, error_nan,
                                                                            error_time))
    print('avg_use : {}'.format(sum(use_time_list) / len(use_time_list)))
    print('max_use : {}'.format(max(use_time_list)))
    print('min_use : {}'.format(min(use_time_list)))
    print('avg_tps : {}'.format(sum(tps_list) / len(tps_list)))
    print('max_tps : {}'.format(max(tps_list)))
    print('min_tps : {}'.format(min(tps_list)))
    print('#' * 30)


def loop(i):
    # 单个线程执行数
    # for j in range(1):
    while True:
        print('接口请求时间 : {}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())))
        run(i)


# 线程数
w = 2
th_list = []

for i in range(w):
    t = threading.Thread(target=loop, args=(i,))
    t.start()
    th_list.append(t)

for t in th_list:
    t.join()

if __name__ == '__main__':
    t1 = time.time()
    send_request()
    t2 = time.time()
    print("cost:", t2 - t1)
